<style scoped>
.upload-list img {
    height: 62px;
}
</style>
<template>
    <!-- 图片上传缩略图 -->
    <div>
        <Upload
            :disabled="disabled"
            ref="upload"
            :multiple="multiple"
            :show-upload-list="true"
            :on-success="handleSuccess"
            :on-error="handleError"
            :format="format"
            :accept="accept"
            :max-size="maxSize"
            :on-progress="handleProgress"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-remove="handleRemove"
            :before-upload="handleBeforeUpload"
            :on-preview="handlePreview"
            type="drag"
            :action="uploadFileUrl"
            :default-file-list="defaultList"
            style="display: inline-block; width: 100%"
        >
            <div style="padding: 20px 0">
                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                <p>点击或移动文件上传</p>
            </div>
        </Upload>

        <!-- <div class="abc upload-list" v-for="(item,index) in uploadList" :key="index">
      <div v-if="item.status == 'finished'">
        <div class="upload-list-cover">
          <span @click="downloadFile(item.url)">
            <i class="ivu-icon ivu-icon-md-document"></i>
            {{item.url.split("=")[1]}}
          </span>
          <i
            class="ivu-icon ivu-icon-ios-close ivu-upload-list-remove"
            style
            @click="handleRemove(item)"
          ></i>
        </div>
      </div>
      <div v-else>
        <Progress :percent="item.percentage"></Progress>
      </div>
    </div>-->
    </div>
</template>

<script>
import Cookies from 'js-cookie';

export default {
    name: 'uploadFile',
    props: {
        uploadFileUrl: {
            type: String,
            default: ''
        },
        value: Object,
        multiple: {
            type: Boolean,
            default: true
        },
        disabled: {
            type: Boolean,
            default: false
        },
        format: {
            type: Array,
            default: () => []
        },
        fileNumber: {
            type: Number,
            default: -1
        }
    },
    computed: {
        accept() {
            return this.format.map(item => '.' + item).join(',');
        }
    },
    data() {
        return {
            maxSize: 1024 * 100,
            uploadList: [],
            defaultList: [],
            isComplete: {},
            dateFlag: new Date().getTime(),
            viewImage: false,
            imgUrl: '',
            number: 0
        };
    },
    methods: {
        init() {},
        handleView(imgUrl) {
            this.imgUrl = imgUrl;
            this.viewImage = true;
        },
        handleRemove(file) {
            this.uploadList = this.uploadList.filter(item => item.uid != file.uid);
            this.defaultList = this.defaultList.filter(item => item.uid != file.uid);
            this.number--;
            this.returnValue();
        },
        handleProgress(event, file, fileList) {
            this.uploadList = fileList;
            if (file && file.uid) this.isComplete[file.uid] = false;
            // 调用监听 上传进度 的事件
            event.target.onprogress = event => {
                let uploadPercent = parseFloat(((event.loaded / event.total) * 100).toFixed(2)); // 保留两位小数，具体根据自己需求做更改
                // 手动设置显示上传进度条 以及上传百分比
                file.showProgress = true;
                file.percentage = uploadPercent;
            };
        },
        handleSuccess(res, file) {
            this.isComplete[file.uid] = true;
            if (!res.group_name) {
                this.handleRemove(file);
                // this.$Message.error('文件上传失败,请重新上传');
                this.$Message.error({
                    content: '文件上传失败,请重新上传',
                    duration: 5,
                    closable: true
                });
                return;
            }
            file.url = `/download?group_name=${res.group_name}&appender_filename=${res.appender_filename}`;
            //file.url = config.base + res.result;
            // 单张图片处理
            // if (!this.multiple && this.uploadList.length > 0) {
            //   // 删除第一张
            //   this.uploadList.splice(0, 1);
            // }
            //this.uploadList.push(file);
            // 返回组件值
            this.returnValue();
        },
        handleError(error, file, fileList) {
            this.isComplete[file.uid] = true;
            this.handleRemove(file);
            // this.$Message.error(error.toString());
            this.$Message.error({
                content: '文件上传失败,请重新上传',
                duration: 5,
                closable: true
            });
        },
        handleFormatError(file) {
            //移除上传不正确的文件
            this.handleRemove(file);
            let formatStr = this.format.join('|');
            this.$Notice.warning({
                title: '不支持的文件格式',
                desc: '所选文件‘ ' + file.name + ' ’格式不正确, 请选择 ' + formatStr + '格式文件'
            });
        },
        handleMaxSize(file) {
            this.$Notice.warning({
                title: '文件大小过大',
                desc: '所选文件‘ ' + file.name + ' ’大小过大, 不得超过  ${this.maxSize / 1024}M.'
            });
        },
        //检查是否上传完成了
        validateComplete() {
            let isComplete = true;
            for (let attr in this.isComplete) {
                if (attr && this.isComplete[attr] == false) {
                    isComplete = false;
                    break;
                }
            }
            return isComplete;
        },
        handleBeforeUpload(file) {
            if (this.fileNumber != -1 && this.fileNumber % 1 == 0 && this.number >= this.fileNumber) {
                var currentTime = new Date().getTime();
                if (currentTime - this.dateFlag > 1.5 * 1000) {
                    this.$Message.warning('只能上传' + this.fileNumber + '个文件，请移除文件再上传');
                    this.dateFlag = currentTime;
                }
                return false;
            }
            this.number++;
            return true;
        },
        returnValue() {
            if (!this.uploadList || this.uploadList.length < 1) {
                this.$emit('on-change', '');
                return;
            }
            if (!this.multiple) {
                // 单张
                let v = this.uploadList[0].url;
                this.$emit('on-change', v);
            } else {
                let v = this.uploadList.map(e => e.url).join(',');
                this.$emit('on-change', v);
            }
        },
        setData(v) {
            if (typeof v == 'string' && v) {
                let arr = v.split(',');
                this.defaultList = arr.map(b => {
                    let split = b.split('=');
                    return {
                        name: b.split('=').length > 1 ? split[split.length - 1] : '',
                        url: b,
                        status: 'finished'
                    };
                });
            } else if (typeof v == 'object') {
                this.defaultList = v.map(e => {
                    return {
                        url: e,
                        status: 'finished'
                    };
                });
            } else {
                this.$refs.upload.clearFiles();
                this.defaultList = [];
                this.isComplete = {};
            }
            this.uploadList = this.defaultList;
            this.number = this.uploadList.length;
            this.returnValue();
        },
        downloadFile(v) {
            window.location = v;
        },
        handlePreview(file) {
            window.location.href = file.url;
        },
        computedNumber() {
            if (this.fileNumber % 1 != 0) {
                // this.$Message.error("fileNumber 只能为整数或为空表示上传不限制个数");
                this.$Message.error({
                    content: 'fileNumber 只能为整数或为空表示上传不限制个数',
                    duration: 5,
                    closable: true
                });
                return;
            }
            if (this.multiple == false) {
                this.fileNumber = 1;
            }
            //multiple  true  多个    false 单个
            //数量
            else if (this.fileNumber == 1) {
                this.multiple = false;
            }
        }
    },
    mounted() {
        this.init();
        this.computedNumber();
    }
};
</script>

<style lang="less">
.upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 5px;
}
.upload-list img {
    width: 100%;
    height: 100%;
}
.upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
}
.upload-list:hover .upload-list-cover {
    display: block;
}
.upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
}
</style>
